package comAssistant;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.etonedu.meals.service.CardService;
import com.etonedu.meals.utils.Utils;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.LinkedList;
import java.util.Queue;

import comAssistant.bean.ComBean;

/**
 * Created by Administrator on 2016/10/9.
 */

public class ComAssistantUtils {
    private static Context mContext;
    private SerialControl serialControl;
    private SerialControl serialControl1;
    private DispQueueThread dispQueue;//刷新显示线程
    private static ComAssistantUtils comAssistantUtils;

    private Handler handler;

    private ComAssistantUtils(){
        int version = Utils.getAndroidSDKVersion();
        String model = Build.MODEL;
        String cpuInfo = Build.CPU_ABI;
        LogUtils.e("model = "+model);
        LogUtils.e("version = " + version);
        LogUtils.e("cpuInfo = "+cpuInfo);
        if (version == Build.VERSION_CODES.LOLLIPOP_MR1 || "rk3288_box".equals(model)) {
            if ("ZK-R329".equals(model)) {
                serialControl = new SerialControl("/dev/ttyS4", "19200");
                serialControl1 = new SerialControl("/dev/ttyS1", "19200");
            } else {
                serialControl = new SerialControl("/dev/ttyS3", "9600");
            }
        } else {
            if("M3".equals(model) || "rk3288".equals(model)) {
                serialControl = new SerialControl("/dev/ttyS3", "9600");

            } else if("SoftwinerEvb".equals(model)) {
                serialControl = new SerialControl("/dev/ttyS7", "9600");
            } else if ("rk3188".equals(model)) {
                serialControl = new SerialControl("/dev/ttyS1", "4800");
            } else if ("B215ANL".equals(model)) {
                serialControl = new SerialControl("/dev/ttyS3", "9600");
            } else {
                serialControl = new SerialControl("/dev/ttyS3", "9600");
            }
        }

//        serialControl = new SerialControl("/dev/ttyS4", "9600");
        dispQueue = new DispQueueThread();
        dispQueue.start();
    }

    public static ComAssistantUtils getInstance(Context context) {
        mContext = context;
        if (comAssistantUtils == null) {
            comAssistantUtils = new ComAssistantUtils();
        }
        return comAssistantUtils;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    //----------------------------------------------------串口控制类
    private class SerialControl extends SerialHelper{

        //		public SerialControl(String sPort, String sBaudRate){
//			super(sPort, sBaudRate);
//		}
        public SerialControl(){
        }
        public SerialControl(String sPort, String sBaudRate) {
            super(sPort,sBaudRate);
        }

        @Override
        protected void onDataReceived(final ComBean comRecData)
        {
            //数据接收量大或接收时弹出软键盘，界面会卡顿,可能和6410的显示性能有关
            //直接刷新显示，接收数据量大时，卡顿明显，但接收与显示同步。
            //用线程定时刷新显示可以获得较流畅的显示效果，但是接收数据速度快于显示速度时，显示会滞后。
            //最终效果差不多-_-，线程定时刷新稍好一些。
            if (comRecData != null) {
                String data = dispRecData(comRecData,false);
                LogUtils.e("data = "+data);
            }
            dispQueue.addQueue(comRecData);//线程定时刷新显示(推荐)
			/*
			runOnUiThread(new Runnable()//直接刷新显示
			{
				public void run()
				{
					DispRecData(ComRecData);
				}
			});*/
        }
    }
    //----------------------------------------------------刷新显示线程
    private class DispQueueThread extends Thread {
        private Queue<ComBean> QueueList = new LinkedList<ComBean>();
        @Override
        public void run() {
            super.run();
            while(!isInterrupted()) {
                final ComBean comData;
                while((comData = QueueList.poll()) != null)
                {
                    String data = dispRecData(comData,false);
                    LogUtils.e("data = "+data);
                    if (TextUtils.isEmpty(data)) return;
                    LogUtils.e("data = "+data);
                    handler.obtainMessage(CardService.SERIAL,data).sendToTarget();
                    String model = Build.MODEL;
                    LogUtils.e("model = "+model);
                    if ("rk3188".equals(model)) {
                        try {
                            Thread.sleep(100);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            Thread.sleep(50);//显示性能高的话，可以把此数值调小。
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                }
            }
        }

        public synchronized void addQueue(ComBean ComData){
            QueueList.add(ComData);
        }
    }

    //----------------------------------------------------显示接收数据
    private String dispRecData(ComBean comRecData, boolean isTxt){
        StringBuilder sMsg = new StringBuilder();
        /*sMsg.append(comRecData.sRecTime);
        sMsg.append("[");
        sMsg.append(comRecData.sComPort);
        sMsg.append("]");

        if (isTxt)
        {
            sMsg.append("[Txt] ");
            sMsg.append(new String(comRecData.bRec));
        }else {
            sMsg.append("[Hex] ");
            sMsg.append(MyFunc.ByteArrToHex(comRecData.bRec));
        }*/
        String model = Build.MODEL;
        LogUtils.e(model);
        if ("rk3288".equals(model) || "B215ANL".equals(model)) {
            sMsg.append(new String(comRecData.bRec));
            String msg = new String(comRecData.bRec);
            LogUtils.e("bRec = "+msg);
        } else {
            sMsg.append(MyFunc.ByteArrToHex(comRecData.bRec));
            String msg = MyFunc.ByteArrToHex(comRecData.bRec);
            LogUtils.e("bRec = "+msg);
        }
        LogUtils.e("sMsg = "+sMsg.toString());
        return sMsg.toString();
    }

    //----------------------------------------------------关闭串口
    public void closeComPort(){
        if (serialControl != null){
            serialControl.stopSend();
            serialControl.close();
        }
        if (serialControl1 != null) {
            serialControl1.stopSend();
            serialControl1.close();
        }
    }
    //----------------------------------------------------打开串口
    public void openComPort(){
        try
        {
            if(serialControl != null) {
                serialControl.open();
                LogUtils.e("打开串口");
            }
            if (serialControl1 != null) {
                serialControl1.open();
            }
        } catch (SecurityException e) {
            showMessage(mContext,"打开串口失败:没有串口读/写权限!");
            e.printStackTrace();
        } catch (IOException e) {
            showMessage(mContext,"打开串口失败:未知错误!");
        } catch (InvalidParameterException e) {
            showMessage(mContext,"打开串口失败:参数错误!");
        }
    }
    //------------------------------------------显示消息
    private void showMessage(Context context, String sMsg)
    {
        Toast.makeText(context, sMsg, Toast.LENGTH_SHORT).show();
    }

    private void sendPortData(SerialHelper ComPort, String sOut){
        if (ComPort!=null && ComPort.isOpen())
        {
            ComPort.sendHex(sOut);
        }
    }

    public void sendPortData(String sOut) {
        sendPortData(serialControl,sOut);
    }
}
